import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getCurrUserInfoAPI } from '@/apis/user'
import { addRouteByRoles, resetRouter } from '@/router'

export const useUserStore = defineStore('user', () => {

  const userInfo = ref(null)

  const us = ref({
    loggedUseId: '',
    isLogged: false,
    isActive: false,
    isNotActive: false,
    isBanned: false,
    isAdmin: false,
    isStaff: false,
  })

  const getUserInfo = () => userInfo.value
  const refreshUserInfo = async () => {
    const res = await getCurrUserInfoAPI() // 401 在http拦截器处理
    setUserInfo(res.data)
  }
  const setUserInfo = (info) => {
    userInfo.value = info
    const { roles } = info

    addRouteByRoles(roles)
  }

  const clearUserInfo = () => {
    resetRouter()
    _reset()
  }

  watch(userInfo, () => _deriveUserState(), { immediate: true })

  function _reset() {
    userInfo.value = null
  }

  function _deriveUserState() {
    const info = userInfo.value

    us.value.isLogged = info ? true : false
    us.value.loggedUseId = info ? info.user.id : ''
    us.value.isActive = us.value.isLogged && info.user.status == 'active'
    us.value.isNotActive = us.value.isLogged && info.user.status == 'suspend'
    us.value.isBanned = us.value.isLogged && info.user.status == 'banned'
    us.value.isAdmin = us.value.isLogged && info.roles.some(v => v == 'admin')
    us.value.isStaff = us.value.isLogged && (info.roles.some(v => v == 'staff') || us.value.isAdmin)
  }

  return {
    userInfo,
    us,
    setUserInfo,
    getUserInfo,
    refreshUserInfo,
    clearUserInfo,
  }
})